# -*- coding: utf-8 -*-
import flask,os,sys,time
from flask import request, send_from_directory,g
import trans
# from  gevent.pywsgi import WSGIServer
# from werkzeug.contrib.fixers import ProxyFix
# from gevent import monkey

# interface_path = os.path.dirname(__file__)
# sys.path.insert(0, interface_path)  #将当前文件的父目录加入临时系统变量


server = flask.Flask(__name__)


@server.route('/')
def hello():
    return 'hello'

@server.route('/test')
def lalal():
    return 'test'

# post方法：上传文件的
@server.route('/upload', methods=['post'])
def upload():
    # fname = request.files.get('file')  #获取上传的文件
    fpath='upload/'
    fname = request.files['file']  #获取上传的文件
    # 全局上下文
    g.DEFAULT_SRC_LANGUAGE=request.form['DEFAULT_SRC_LANGUAGE']
    print('g.DEFAULT_SRC_LANGUAGE===>'+g.DEFAULT_SRC_LANGUAGE)
    g.diglossia=request.form['diglossia']
    print('g.diglossia===>'+g.diglossia)

    g.DEFAULT_DST_LANGUAGE=request.form['DEFAULT_DST_LANGUAGE']
    print('g.DEFAULT_DST_LANGUAGE===>'+g.DEFAULT_DST_LANGUAGE)

    # 从客户端传来的只有文件名,不包含路径
    print('fname.filename===>'+fname.filename)
    if fname:
        # 保存到本机的upload目录,写一个判断函数,如果没有就建立一个
        new_fname = r'upload/'+ fname.filename
        print('new_fname==>'+new_fname)
        fname.save(new_fname)  #保存文件到指定路径
        
        trans.translate_file(new_fname,g.DEFAULT_SRC_LANGUAGE,g.DEFAULT_DST_LANGUAGE,g.diglossia)

        fname.filename = os.path.splitext(fname.filename)[0]+'.srt'
        print('开始返回文件数据')
        if fname.filename.strip() and fpath.strip():
            print(fname.filename, fpath)
            if os.path.isfile(os.path.join(fpath,fname.filename)) and os.path.isdir(fpath):
                print('返回数据成功')
                return send_from_directory(fpath,fname.filename, as_attachment=True) #返回要下载的文件内容给客户端
                os.remove(new_fname)
                os.remove(os.path.join(fpath,fname.filename))
            else:
                return '{"msg":"解析成功,下载数据异常"}'
        else:
            return '{"msg":"文件名或者文件夹异常"}'

# server.debug = True
server.run(host="0.0.0.0",port=5000)
# server.run()


# server.wsgi_app = ProxyFix(server.wsgi_app)
# server.run(host="0.0.0.0",port=5000)
 
if __name__ == '__main__':
    # server.debug = True
    # server.run()
    server.run(host="0.0.0.0",port=5000)
